/*
 * @Author: your name
 * @Date: 2022-03-29 14:28:42
 * @LastEditTime: 2022-09-19 14:53:34
 * @LastEditors: DT1604\ZPL zhoupeili@dpc.com.cn
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \operation-platform-ui\src\utils\request.js
 */
import axios from 'axios';
import store from '@/store';
import storage from 'store';
import notification from 'ant-design-vue/es/notification';
// import { VueAxios } from './axios';
import {
  ACCESS_TOKEN
} from '@/store/mutation-types';
const service = axios.create({
  baseURL: 'https://testzh.dpcpower.com',//测试环境
  // baseURL: 'https://zh.dpcpower.com',//生产环境
  // baseURL: 'http://172.16.151.40:8002',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
});
// 异常拦截处理器
const errorHandler = error => {
  console.log(error)
  if (error.response) {
    const data = error.response.data;
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN);
    if (error.response.status == 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      });
    }
    if (error.response.status == 500 || error.response.status == 502) {
      notification.error({
        message: '服务器错误',
        description: data.message
      });
    }
    if (error.response.status == 401 && !(data.result && data.result.isLogin)) {
      // notification.error({
      //   message: 'Unauthorized',
      //   description: 'Authorization verification failed'
      // });
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload();
          }, 1500);
        });
      }
    }
  }
  else{
    notification.error({
      message:'提示',
      description: error.Error
    });
  }
  return Promise.reject(error);
};

// request interceptor
service.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN);
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = token;
  }
  config.headers['X-Requested-With'] = 'XMLHttpRequest ';
  return config;
}, errorHandler);

// response interceptor
service.interceptors.response.use(response => {
  let data = response.data;
  if(data.code == 401){
    store.dispatch('Logout').then(() => {
      setTimeout(() => {
        window.location.reload();
      }, 1500);
    });
  }
  else if(data.code && data.code != 200){
    notification.error({
      message:'提示',
      description: data.message
    });
  }
  return response.data;
}, errorHandler);
export default service;
// const installer = {
//   vm: {},
//   install(Vue) {
//     Vue.use(VueAxios, axios);
//   }
// };

// export default axios;

// export { installer as VueAxios, axios };